package cn.gyouzhe.utils;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.URLEncoder;

/**
 * URL工具
 *
 * @author wangchuan
 * @createTime 2017/11/7 14:18
 */
@Slf4j
public class Url {
    /**
     * 链接地址
     */
    private String url;

    private Url(UrlBuilder builder) {
        this.url = builder.urlBuilder.toString();
    }

    public String getUrl() {
        return this.url;
    }

    public static UrlBuilder create() {
        return new UrlBuilder();
    }

    public static class UrlBuilder {
        private StringBuilder urlBuilder;

        private UrlBuilder() {
        }

        /**
         * 验证是否传入URL
         */
        private void check() {
            if(null == urlBuilder) {
                log.error("未传入URL的情况下添加参数");
                throw new RuntimeException("未传入URL的情况下添加参数");
            }
        }

        /**
         * 初始化url
         * @param url 请求URL
         * @return 构建器
         */
        public UrlBuilder url(String url) {
            if(StringUtils.isEmpty(url)) {
                log.error("传入的URL为空");
                throw new RuntimeException("传入的URL为空");
            }
            this.urlBuilder = new StringBuilder(url);
            return this;
        }

        /**
         * 添加请求参数
         *
         * @param key  参数名
         * @param value 参数值
         */
        public UrlBuilder appendQuery(String key, String value) {
            check();
            try {
                this.urlBuilder.append(StringUtils.contains(urlBuilder, "?") ? "&" : "?").append(key).append("=").append(URLEncoder.encode(value, "UTF-8"));
                return this;
            } catch(Exception e) {
                log.error("添加请求参数异常", e);
                throw new RuntimeException(e);
            }
        }

        public Url build() {
            check();
            return new Url(this);
        }


    }
}
